package com.gxa.meiye.core.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Set;

/**
 * @author chen
 * @date 2022/7/7 16:40
 */
public class RestUtils {

    private static RestTemplate restTemplate ;

    static{
        // OkHttp3ClientHttp性能比较好, 需要引入jar
       // restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());
        restTemplate = new RestTemplate();
    }

    /**
     *
     * @param url
     * @param headers 自定义请求头,null表示没有需要传递的请求头
     * @return
     */
    public static Map postWithParams(String url, Map<String,String> headers, MultiValueMap params){

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        if(headers != null){
            Set<Map.Entry<String, String>> entries = headers.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                httpHeaders.set(entry.getKey(),entry.getValue());
            }
        }

        HttpEntity httpEntity = new HttpEntity(params,httpHeaders);

        // 通过post方式发送请求的方法
        Map map = restTemplate.postForObject(url, httpEntity, Map.class);
        return map;
    }

    /**
     * 通过参数发起远程请求的重载方法
     * @param url 请求地址
     * @param params 请求参数
     * @return 请求到的Map接口
     */
    public static Map postWithParams(String url, MultiValueMap params){
        Map map = postWithParams(url, null, params);
        return map;
    }
}
